﻿#encoding=utf-8

import hashlib
import hmac
import urllib
from base64 import b64encode
from tornado.web import RequestHandler

class Baidu():
    _access_key = ''
    _secure_key = ''
    _host = 'bcs.duapp.com'
    _bucket = 'xx'
    
    def create_object(self, object, content):
		opt = {}

		opt["ak"]  = self._access_key
		opt["sk"]  = self._secure_key
		opt["bucket"] = self._bucket
		opt["object"] = object
		opt["method"] = 'PUT'
		opt["headers"] = {}
		opt["headers"]["x-bs-acl"] = "public-read"
		url = self.format_url(opt)
		opt["url"] = url
		headers = {}
		headers["Content-Type"] = "image/jpeg"
		headers["x-bs-acl"] = "public-read"
		headers["Content-Length"] = len(content)
		headers["md5"] = ""

		import httplib
		conn = httplib.HTTPConnection(self._host)
		conn.request('PUT', opt["url"], headers = headers)
		conn.send(content)
		conn.close()
		return str(conn.getresponse().read())
		
		
		
    
    def format_url(self,opt):
        sign = self.format_signature(opt)
        opt["sign"] = sign
        url = "http://"+self._host+"/"+self._bucket
        url+= "/"+urllib.quote_plus(opt["object"])
        url+= "?"+sign
        return url
    
    def format_signature(self,opt):
        flags = 'MBO'
        content =  "Method="+opt["method"]+"\n"
        content += "Bucket="+opt["bucket"]+"\n"
        content += "Object="+opt["object"]+"\n"
        
        content = flags+"\n"+content
        sign = b64encode(hmac.new(opt["sk"],content,hashlib.sha1).digest())
        return "sign="+ flags+":"+opt["ak"]+":"+urllib.quote_plus(sign)


